/********************************************************************************
 * Project Name		[JavaEE_Components]
 * File Name     	[LinkUtils.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package javamail.cases.utils;

import java.security.MessageDigest;

import javamail.cases.Constants;
import javamail.cases.bean.User;

/**
 * 用于账户激活, 密码重置的链接生成
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
public class LinkUtils {

	private static final String BASE_URL = "http://localhost:8080/JavaEE_Components/account.do";

	/**
	 * 生成激活链接
	 * 
	 * @param user
	 * @return
	 */
	public static String genderateActivateLink(User user) {
		return BASE_URL + "?id=" + user.getId() + "&" + "method=activateAccount&" + Constants.ACTIVATE_CODE + "="
				+ generateRandomCode(user);
	}

	/**
	 * 生成密码重置连接
	 * 
	 * @param user
	 * @return
	 */
	public static String generateResetPasswordLink(User user) {
		return BASE_URL + "?id=" + user.getId() + "&" + "method=goToResetPage&" + Constants.RESET_CODE + "="
				+ generateRandomCode(user);
	}

	/**
	 * 验证校验码
	 * 
	 * @param user
	 * @param code
	 * @return
	 */
	public static boolean validateRandomCode(User user, String code) {
		return generateRandomCode(user).equals(code);
	}

	/**
	 * 生成随机码
	 * 
	 * @param user
	 * @return
	 */
	private static String generateRandomCode(User user) {
		String username = user.getUsername();
		String password = user.getPassword();
		return generateRandomCodeByMD5(username + password);
	}

	/**
	 * 使用MD5算法的随机码
	 * 
	 * @param source
	 * @return
	 */
	private static String generateRandomCodeByMD5(String source) {
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("md5");
			md.update(source.getBytes());
			byte[] bytes = md.digest();
			return bytesToHex(bytes);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private static String bytesToHex(byte[] bytes) {
		StringBuffer buffer = new StringBuffer(bytes.length * 2);

		for (int i = 0; i < bytes.length; i++) {
			buffer.append(Character.forDigit((bytes[i] & 0xf0) >> 4, 16));
			buffer.append(Character.forDigit(bytes[i] & 0x0f, 16));
		}

		return buffer.toString();
	}
}
